#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
采购订单管理模块
实现采购需求计划生成、多级审批工作流、采购订单执行跟踪、收货确认和质量检验功能
"""

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import os
import json
from pathlib import Path
import uuid

class PurchaseOrderManager:
    """采购订单管理系统核心类"""
    
    def __init__(self, data_path='data/processed'):
        """
        初始化采购订单管理系统
        
        参数:
            data_path: 数据文件路径
        """
        self.data_path = data_path
        self.purchase_orders_df = self._load_or_create_purchase_orders()
        self.purchase_items_df = self._load_or_create_purchase_items()
        self.purchase_requisitions_df = self._load_or_create_purchase_requisitions()
        self.approval_workflows_df = self._load_or_create_approval_workflows()
        self.receipts_df = self._load_or_create_receipts()
        self.quality_inspections_df = self._load_or_create_quality_inspections()
        
        # 加载供应商数据（如果存在）
        try:
            self.suppliers_df = pd.read_csv(os.path.join(self.data_path, 'suppliers.csv'))
        except FileNotFoundError:
            self.suppliers_df = pd.DataFrame({
                'supplier_id': [],
                'name': []
            })
        
        # 加载产品数据（如果存在）
        try:
            self.products_df = pd.read_csv(os.path.join(self.data_path, 'products.csv'))
        except FileNotFoundError:
            self.products_df = pd.DataFrame({
                'product_id': [],
                'name': [],
                'category': [],
                'unit': []
            })
    
    def _load_or_create_purchase_orders(self):
        """加载或创建采购订单数据"""
        file_path = os.path.join(self.data_path, 'purchase_orders.csv')
        try:
            return pd.read_csv(file_path)
        except FileNotFoundError:
            print(f"信息: 未找到采购订单数据文件，将创建新文件")
            df = pd.DataFrame({
                'po_id': [],
                'po_number': [],
                'supplier_id': [],
                'order_date': [],
                'delivery_date': [],
                'status': [],
                'total_amount': [],
                'currency': [],
                'payment_terms': [],
                'shipping_terms': [],
                'created_by': [],
                'approved_by': [],
                'approval_date': [],
                'notes': []
            })
            df.to_csv(file_path, index=False)
            return df
    
    def _load_or_create_purchase_items(self):
        """加载或创建采购订单项数据"""
        file_path = os.path.join(self.data_path, 'purchase_order_items.csv')
        try:
            return pd.read_csv(file_path)
        except FileNotFoundError:
            print(f"信息: 未找到采购订单项数据文件，将创建新文件")
            df = pd.DataFrame({
                'item_id': [],
                'po_id': [],
                'product_id': [],
                'quantity': [],
                'unit_price': [],
                'currency': [],
                'tax_rate': [],
                'delivery_date': [],
                'status': [],
                'received_quantity': [],
                'accepted_quantity': [],
                'rejected_quantity': []
            })
            df.to_csv(file_path, index=False)
            return df
    
    def _load_or_create_purchase_requisitions(self):
        """加载或创建采购申请数据"""
        file_path = os.path.join(self.data_path, 'purchase_requisitions.csv')
        try:
            return pd.read_csv(file_path)
        except FileNotFoundError:
            print(f"信息: 未找到采购申请数据文件，将创建新文件")
            df = pd.DataFrame({
                'requisition_id': [],
                'requisition_number': [],
                'requester': [],
                'department': [],
                'request_date': [],
                'required_date': [],
                'status': [],
                'product_id': [],
                'quantity': [],
                'estimated_price': [],
                'currency': [],
                'purpose': [],
                'notes': [],
                'po_id': []
            })
            df.to_csv(file_path, index=False)
            return df
    
    def _load_or_create_approval_workflows(self):
        """加载或创建审批工作流数据"""
        file_path = os.path.join(self.data_path, 'approval_workflows.csv')
        try:
            return pd.read_csv(file_path)
        except FileNotFoundError:
            print(f"信息: 未找到审批工作流数据文件，将创建新文件")
            df = pd.DataFrame({
                'workflow_id': [],
                'reference_id': [],
                'reference_type': [],
                'approver': [],
                'approval_level': [],
                'status': [],
                'approval_date': [],
                'comments': []
            })
            df.to_csv(file_path, index=False)
            return df
    
    def _load_or_create_receipts(self):
        """加载或创建收货数据"""
        file_path = os.path.join(self.data_path, 'purchase_receipts.csv')
        try:
            return pd.read_csv(file_path)
        except FileNotFoundError:
            print(f"信息: 未找到收货数据文件，将创建新文件")
            df = pd.DataFrame({
                'receipt_id': [],
                'po_id': [],
                'item_id': [],
                'receipt_date': [],
                'received_quantity': [],
                'receiver': [],
                'delivery_note_number': [],
                'carrier': [],
                'status': [],
                'notes': []
            })
            df.to_csv(file_path, index=False)
            return df
    
    def _load_or_create_quality_inspections(self):
        """加载或创建质量检验数据"""
        file_path = os.path.join(self.data_path, 'quality_inspections.csv')
        try:
            return pd.read_csv(file_path)
        except FileNotFoundError:
            print(f"信息: 未找到质量检验数据文件，将创建新文件")
            df = pd.DataFrame({
                'inspection_id': [],
                'receipt_id': [],
                'po_id': [],
                'item_id': [],
                'inspection_date': [],
                'inspector': [],
                'accepted_quantity': [],
                'rejected_quantity': [],
                'rejection_reason': [],
                'status': [],
                'notes': []
            })
            df.to_csv(file_path, index=False)
            return df
    
    def create_purchase_requisition(self, requisition_data):
        """
        创建采购申请
        
        参数:
            requisition_data: 采购申请数据字典
        
        返回:
            采购申请ID
        """
        # 验证必要字段
        required_fields = ['requester', 'department', 'product_id', 'quantity', 'required_date']
        for field in required_fields:
            if field not in requisition_data:
                raise ValueError(f"缺少必要字段: {field}")
        
        # 验证产品是否存在
        if requisition_data['product_id'] not in self.products_df['product_id'].values:
            raise ValueError(f"产品不存在: {requisition_data['product_id']}")
        
        # 生成采购申请ID和编号
        if len(self.purchase_requisitions_df) == 0:
            new_id = "REQ10001"
            new_number = "PR-2025-00001"
        else:
            last_id = self.purchase_requisitions_df['requisition_id'].iloc[-1]
            new_id = f"REQ{int(last_id[3:]) + 1}"
            
            last_number = self.purchase_requisitions_df['requisition_number'].iloc[-1]
            number_parts = last_number.split('-')
            new_number = f"PR-{number_parts[1]}-{int(number_parts[2]) + 1:05d}"
        
        # 添加默认值
        requisition_data['requisition_id'] = new_id
        requisition_data['requisition_number'] = new_number
        requisition_data['request_date'] = requisition_data.get('request_date', datetime.now().strftime('%Y-%m-%d'))
        requisition_data['status'] = '待审批'
        requisition_data['estimated_price'] = requisition_data.get('estimated_price', 0)
        requisition_data['currency'] = requisition_data.get('currency', 'CNY')
        requisition_data['purpose'] = requisition_data.get('purpose', '')
        requisition_data['notes'] = requisition_data.get('notes', '')
        requisition_data['po_id'] = None
        
        # 添加到数据框
        self.purchase_requisitions_df = pd.concat([
            self.purchase_requisitions_df, 
            pd.DataFrame([requisition_data])
        ], ignore_index=True)
        
        # 保存数据
        self.purchase_requisitions_df.to_csv(os.path.join(self.data_path, 'purchase_requisitions.csv'), index=False)
        
        # 创建审批工作流
        self._create_approval_workflow(new_id, 'requisition')
        
        return new_id
    
    def _create_approval_workflow(self, reference_id, reference_type):
        """
        创建审批工作流
        
        参数:
            reference_id: 引用ID（采购申请ID或采购订单ID）
            reference_type: 引用类型（'requisition'或'order'）
        """
        # 根据引用类型确定审批级别
        if reference_type == 'requisition':
            # 采购申请通常需要两级审批：部门经理和采购经理
            approvers = [
                {'approver': '部门经理', 'level': 1},
                {'approver': '采购经理', 'level': 2}
            ]
        else:  # 'order'
            # 采购订单通常需要三级审批：采购经理、财务经理和总经理
            approvers = [
                {'approver': '采购经理', 'level': 1},
                {'approver': '财务经理', 'level': 2},
                {'approver': '总经理', 'level': 3}
            ]
        
        # 创建工作流记录
        for approver_info in approvers:
            workflow_data = {
                'workflow_id': str(uuid.uuid4()),
                'reference_id': reference_id,
                'reference_type': reference_type,
                'approver': approver_info['approver'],
                'approval_level': approver_info['level'],
                'status': '待审批' if approver_info['level'] == 1 else '等待前序审批',
                'approval_date': None,
                'comments': None
            }
            
            # 添加到数据框
            self.approval_workflows_df = pd.concat([
                self.approval_workflows_df, 
                pd.DataFrame([workflow_data])
            ], ignore_index=True)
        
        # 保存数据
        self.approval_workflows_df.to_csv(os.path.join(self.data_path, 'approval_workflows.csv'), index=False)
    
    def approve_workflow(self, reference_id, reference_type, approver, status, comments=None):
        """
        审批工作流
        
        参数:
            reference_id: 引用ID
            reference_type: 引用类型
            approver: 审批人
            status: 审批状态（'通过'或'拒绝'）
            comments: 审批意见
        
        返回:
            审批是否成功
        """
        # 查找当前待审批的工作流
        current_workflow = self.approval_workflows_df[
            (self.approval_workflows_df['reference_id'] == reference_id) &
            (self.approval_workflows_df['reference_type'] == reference_type) &
            (self.approval_workflows_df['approver'] == approver) &
            (self.approval_workflows_df['status'] == '待审批')
        ]
        
        if len(current_workflow) == 0:
            return False
        
        # 更新当前工作流状态
        workflow_idx = current_workflow.index[0]
        self.approval_workflows_df.loc[workflow_idx, 'status'] = status
        self.approval_workflows_df.loc[workflow_idx, 'approval_date'] = datetime.now().strftime('%Y-%m-%d')
        if comments:
            self.approval_workflows_df.loc[workflow_idx, 'comments'] = comments
        
        # 如果审批通过，更新下一级审批状态
        if status == '通过':
            current_level = current_workflow['approval_level'].iloc[0]
            next_workflow = self.approval_workflows_df[
                (self.approval_workflows_df['reference_id'] == reference_id) &
                (self.approval_workflows_df['reference_type'] == reference_type) &
                (self.approval_workflows_df['approval_level'] == current_level + 1) &
                (self.approval_workflows_df['status'] == '等待前序审批')
            ]
            
            if len(next_workflow) > 0:
                next_idx = next_workflow.index[0]
                self.approval_workflows_df.loc[next_idx, 'status'] = '待审批'
        
        # 保存数据
        self.approval_workflows_df.to_csv(os.path.join(self.data_path, 'approval_workflows.csv'), index=False)
        
        # 更新引用对象状态
        self._update_reference_status(reference_id, reference_type, status)
        
        return True
    
    def _update_reference_status(self, reference_id, reference_type, approval_status):
        """
        更新引用对象状态
        
        参数:
            reference_id: 引用ID
            reference_type: 引用类型
            approval_status: 审批状态
        """
        if reference_type == 'requisition':
            # 获取该申请的所有审批记录
            requisition_workflows = self.approval_workflows_df[
                (self.approval_workflows_df['reference_id'] == reference_id) &
                (self.approval_workflows_df['reference_type'] == 'requisition')
            ]
            
            if approval_status == '拒绝':
                # 任何一级拒绝，整个申请被拒绝
                self.purchase_requisitions_df.loc[
                    self.purchase_requisitions_df['requisition_id'] == reference_id, 
                    'status'
                ] = '已拒绝'
            elif all(status in ['通过', '拒绝'] for status in requisition_workflows['status']):
                if all(status == '通过' for status in requisition_workflows['status']):
                    # 所有级别都通过，申请被批准
                    self.purchase_requisitions_df.loc[
                        self.purchase_requisitions_df['requisition_id'] == reference_id, 
                        'status'
                    ] = '已批准'
            
            # 保存数据
            self.purchase_requisitions_df.to_csv(os.path.join(self.data_path, 'purchase_requisitions.csv'), index=False)
        
        elif reference_type == 'order':
            # 获取该订单的所有审批记录
            order_workflows = self.approval_workflows_df[
                (self.approval_workflows_df['reference_id'] == reference_id) &
                (self.approval_workflows_df['reference_type'] == 'order')
            ]
            
            if approval_status == '拒绝':
                # 任何一级拒绝，整个订单被拒绝
                self.purchase_orders_df.loc[
                    self.purchase_orders_df['po_id'] == reference_id, 
                    'status'
                ] = '已拒绝'
            elif all(status in ['通过', '拒绝'] for status in order_workflows['status']):
                if all(status == '通过' for status in order_workflows['status']):
                    # 所有级别都通过，订单被确认
                    self.purchase_orders_df.loc[
                        self.purchase_orders_df['po_id'] == reference_id, 
                        'status'
                    ] = '已确认'
                    
                    # 更新审批人和审批日期
                    last_approver = order_workflows.sort_values('approval_level', ascending=False)['approver'].iloc[0]
                    approval_date = datetime.now().strftime('%Y-%m-%d')
                    
                    self.purchase_orders_df.loc[
                        self.purchase_orders_df['po_id'] == reference_id, 
                        ['approved_by', 'approval_date']
                    ] = [last_approver, approval_date]
            
            # 保存数据
            self.purchase_orders_df.to_csv(os.path.join(self.data_path, 'purchase_orders.csv'), index=False)
    
    def get_approval_status(self, reference_id, reference_type):
        """
        获取审批状态
        
        参数:
            reference_id: 引用ID
            reference_type: 引用类型
        
        返回:
            审批状态列表
        """
        workflows = self.approval_workflows_df[
            (self.approval_workflows_df['reference_id'] == reference_id) &
            (self.approval_workflows_df['reference_type'] == reference_type)
        ].sort_values('approval_level')
        
        return workflows.to_dict('records')
    
    def create_purchase_order_from_requisition(self, requisition_ids, supplier_id, order_data=None):
        """
        从采购申请创建采购订单
        
        参数:
            requisition_ids: 采购申请ID列表
            supplier_id: 供应商ID
            order_data: 订单附加数据
        
        返回:
            采购订单ID
        """
        # 验证供应商是否存在
        if supplier_id not in self.suppliers_df['supplier_id'].values:
            raise ValueError(f"供应商不存在: {supplier_id}")
        
        # 验证采购申请是否存在且已批准
        requisitions = []
        for req_id in requisition_ids:
            req = self.purchase_requisitions_df[self.purchase_requisitions_df['requisition_id'] == req_id]
            if len(req) == 0:
                raise ValueError(f"采购申请不存在: {req_id}")
            if req['status'].iloc[0] != '已批准':
                raise ValueError(f"采购申请未批准: {req_id}")
            if not pd.isna(req['po_id'].iloc[0]):
                raise ValueError(f"采购申请已关联订单: {req_id}")
            requisitions.append(req)
        
        # 生成采购订单ID和编号
        if len(self.purchase_orders_df) == 0:
            new_id = "PO10001"
            new_number = "PO-2025-00001"
        else:
            last_id = self.purchase_orders_df['po_id'].iloc[-1]
            new_id = f"PO{int(last_id[2:]) + 1}"
            
            last_number = self.purchase_orders_df['po_number'].iloc[-1]
            number_parts = last_number.split('-')
            new_number = f"PO-{number_parts[1]}-{int(number_parts[2]) + 1:05d}"
        
        # 准备订单数据
        if order_data is None:
            order_data = {}
        
        order_data['po_id'] = new_id
        order_data['po_number'] = new_number
        order_data['supplier_id'] = supplier_id
        order_data['order_date'] = order_data.get('order_date', datetime.now().strftime('%Y-%m-%d'))
        
        # 计算最晚交货日期
        delivery_dates = [req['required_date'].iloc[0] for req in requisitions]
        order_data['delivery_date'] = order_data.get('delivery_date', max(delivery_dates))
        
        order_data['status'] = '待审批'
        order_data['currency'] = order_data.get('currency', 'CNY')
        order_data['payment_terms'] = order_data.get('payment_terms', '月结30天')
        order_data['shipping_terms'] = order_data.get('shipping_terms', 'FOB')
        order_data['created_by'] = order_data.get('created_by', '系统')
        order_data['approved_by'] = None
        order_data['approval_date'] = None
        order_data['notes'] = order_data.get('notes', '')
        
        # 添加到数据框
        self.purchase_orders_df = pd.concat([
            self.purchase_orders_df, 
            pd.DataFrame([order_data])
        ], ignore_index=True)
        
        # 创建订单项
        total_amount = 0
        for req in requisitions:
            req_data = req.iloc[0]
            
            # 获取产品信息
            product_id = req_data['product_id']
            product = self.products_df[self.products_df['product_id'] == product_id].iloc[0]
            
            # 准备订单项数据
            item_data = {
                'item_id': str(uuid.uuid4()),
                'po_id': new_id,
                'product_id': product_id,
                'quantity': req_data['quantity'],
                'unit_price': req_data['estimated_price'],
                'currency': req_data['currency'],
                'tax_rate': 0.13,  # 默认增值税率
                'delivery_date': req_data['required_date'],
                'status': '待确认',
                'received_quantity': 0,
                'accepted_quantity': 0,
                'rejected_quantity': 0
            }
            
            # 添加到数据框
            self.purchase_items_df = pd.concat([
                self.purchase_items_df, 
                pd.DataFrame([item_data])
            ], ignore_index=True)
            
            # 更新采购申请关联的订单ID
            self.purchase_requisitions_df.loc[
                self.purchase_requisitions_df['requisition_id'] == req_data['requisition_id'], 
                'po_id'
            ] = new_id
            
            # 计算总金额
            total_amount += req_data['quantity'] * req_data['estimated_price']
        
        # 更新订单总金额
        self.purchase_orders_df.loc[
            self.purchase_orders_df['po_id'] == new_id, 
            'total_amount'
        ] = total_amount
        
        # 保存数据
        self.purchase_orders_df.to_csv(os.path.join(self.data_path, 'purchase_orders.csv'), index=False)
        self.purchase_items_df.to_csv(os.path.join(self.data_path, 'purchase_order_items.csv'), index=False)
        self.purchase_requisitions_df.to_csv(os.path.join(self.data_path, 'purchase_requisitions.csv'), index=False)
        
        # 创建审批工作流
        self._create_approval_workflow(new_id, 'order')
        
        return new_id
    
    def create_purchase_order(self, supplier_id, items, order_data=None):
        """
        直接创建采购订单（不通过申请）
        
        参数:
            supplier_id: 供应商ID
            items: 订单项列表
            order_data: 订单附加数据
        
        返回:
            采购订单ID
        """
        # 验证供应商是否存在
        if supplier_id not in self.suppliers_df['supplier_id'].values:
            raise ValueError(f"供应商不存在: {supplier_id}")
        
        # 验证订单项
        if not items or len(items) == 0:
            raise ValueError("订单项不能为空")
        
        for item in items:
            if 'product_id' not in item or 'quantity' not in item or 'unit_price' not in item:
                raise ValueError("订单项缺少必要字段: product_id, quantity, unit_price")
            
            if item['product_id'] not in self.products_df['product_id'].values:
                raise ValueError(f"产品不存在: {item['product_id']}")
        
        # 生成采购订单ID和编号
        if len(self.purchase_orders_df) == 0:
            new_id = "PO10001"
            new_number = "PO-2025-00001"
        else:
            last_id = self.purchase_orders_df['po_id'].iloc[-1]
            new_id = f"PO{int(last_id[2:]) + 1}"
            
            last_number = self.purchase_orders_df['po_number'].iloc[-1]
            number_parts = last_number.split('-')
            new_number = f"PO-{number_parts[1]}-{int(number_parts[2]) + 1:05d}"
        
        # 准备订单数据
        if order_data is None:
            order_data = {}
        
        order_data['po_id'] = new_id
        order_data['po_number'] = new_number
        order_data['supplier_id'] = supplier_id
        order_data['order_date'] = order_data.get('order_date', datetime.now().strftime('%Y-%m-%d'))
        order_data['delivery_date'] = order_data.get('delivery_date', (datetime.now() + timedelta(days=30)).strftime('%Y-%m-%d'))
        order_data['status'] = '待审批'
        order_data['currency'] = order_data.get('currency', 'CNY')
        order_data['payment_terms'] = order_data.get('payment_terms', '月结30天')
        order_data['shipping_terms'] = order_data.get('shipping_terms', 'FOB')
        order_data['created_by'] = order_data.get('created_by', '系统')
        order_data['approved_by'] = None
        order_data['approval_date'] = None
        order_data['notes'] = order_data.get('notes', '')
        
        # 添加到数据框
        self.purchase_orders_df = pd.concat([
            self.purchase_orders_df, 
            pd.DataFrame([order_data])
        ], ignore_index=True)
        
        # 创建订单项
        total_amount = 0
        for item in items:
            # 准备订单项数据
            item_data = {
                'item_id': str(uuid.uuid4()),
                'po_id': new_id,
                'product_id': item['product_id'],
                'quantity': item['quantity'],
                'unit_price': item['unit_price'],
                'currency': item.get('currency', order_data['currency']),
                'tax_rate': item.get('tax_rate', 0.13),
                'delivery_date': item.get('delivery_date', order_data['delivery_date']),
                'status': '待确认',
                'received_quantity': 0,
                'accepted_quantity': 0,
                'rejected_quantity': 0
            }
            
            # 添加到数据框
            self.purchase_items_df = pd.concat([
                self.purchase_items_df, 
                pd.DataFrame([item_data])
            ], ignore_index=True)
            
            # 计算总金额
            total_amount += item['quantity'] * item['unit_price']
        
        # 更新订单总金额
        self.purchase_orders_df.loc[
            self.purchase_orders_df['po_id'] == new_id, 
            'total_amount'
        ] = total_amount
        
        # 保存数据
        self.purchase_orders_df.to_csv(os.path.join(self.data_path, 'purchase_orders.csv'), index=False)
        self.purchase_items_df.to_csv(os.path.join(self.data_path, 'purchase_order_items.csv'), index=False)
        
        # 创建审批工作流
        self._create_approval_workflow(new_id, 'order')
        
        return new_id
    
    def update_purchase_order(self, po_id, update_data):
        """
        更新采购订单
        
        参数:
            po_id: 采购订单ID
            update_data: 更新数据
        
        返回:
            更新是否成功
        """
        if po_id not in self.purchase_orders_df['po_id'].values:
            return False
        
        # 检查订单状态
        current_status = self.purchase_orders_df.loc[
            self.purchase_orders_df['po_id'] == po_id, 
            'status'
        ].iloc[0]
        
        if current_status not in ['待审批', '已拒绝']:
            return False  # 只有待审批或已拒绝的订单可以更新
        
        # 更新数据
        for key, value in update_data.items():
            if key in self.purchase_orders_df.columns and key not in ['po_id', 'po_number']:
                self.purchase_orders_df.loc[self.purchase_orders_df['po_id'] == po_id, key] = value
        
        # 保存数据
        self.purchase_orders_df.to_csv(os.path.join(self.data_path, 'purchase_orders.csv'), index=False)
        
        return True
    
    def update_purchase_order_item(self, item_id, update_data):
        """
        更新采购订单项
        
        参数:
            item_id: 订单项ID
            update_data: 更新数据
        
        返回:
            更新是否成功
        """
        if item_id not in self.purchase_items_df['item_id'].values:
            return False
        
        # 获取订单ID
        po_id = self.purchase_items_df.loc[
            self.purchase_items_df['item_id'] == item_id, 
            'po_id'
        ].iloc[0]
        
        # 检查订单状态
        current_status = self.purchase_orders_df.loc[
            self.purchase_orders_df['po_id'] == po_id, 
            'status'
        ].iloc[0]
        
        if current_status not in ['待审批', '已拒绝']:
            return False  # 只有待审批或已拒绝的订单可以更新
        
        # 更新数据
        for key, value in update_data.items():
            if key in self.purchase_items_df.columns and key not in ['item_id', 'po_id']:
                self.purchase_items_df.loc[self.purchase_items_df['item_id'] == item_id, key] = value
        
        # 如果更新了数量或单价，重新计算订单总金额
        if 'quantity' in update_data or 'unit_price' in update_data:
            # 计算订单总金额
            order_items = self.purchase_items_df[self.purchase_items_df['po_id'] == po_id]
            total_amount = sum(order_items['quantity'] * order_items['unit_price'])
            
            # 更新订单总金额
            self.purchase_orders_df.loc[
                self.purchase_orders_df['po_id'] == po_id, 
                'total_amount'
            ] = total_amount
            
            # 保存订单数据
            self.purchase_orders_df.to_csv(os.path.join(self.data_path, 'purchase_orders.csv'), index=False)
        
        # 保存订单项数据
        self.purchase_items_df.to_csv(os.path.join(self.data_path, 'purchase_order_items.csv'), index=False)
        
        return True
    
    def get_purchase_order(self, po_id):
        """
        获取采购订单信息
        
        参数:
            po_id: 采购订单ID
        
        返回:
            采购订单信息字典
        """
        if po_id not in self.purchase_orders_df['po_id'].values:
            return None
        
        # 获取订单基本信息
        order_data = self.purchase_orders_df[self.purchase_orders_df['po_id'] == po_id].iloc[0].to_dict()
        
        # 获取订单项
        order_items = self.purchase_items_df[self.purchase_items_df['po_id'] == po_id].to_dict('records')
        order_data['items'] = order_items
        
        # 获取审批状态
        approval_status = self.get_approval_status(po_id, 'order')
        order_data['approval_status'] = approval_status
        
        return order_data
    
    def list_purchase_orders(self, filters=None):
        """
        列出采购订单
        
        参数:
            filters: 过滤条件字典
        
        返回:
            采购订单列表
        """
        result_df = self.purchase_orders_df.copy()
        
        if filters:
            for key, value in filters.items():
                if key in result_df.columns:
                    result_df = result_df[result_df[key] == value]
        
        return result_df.to_dict('records')
    
    def receive_purchase_order(self, po_id, receipt_data):
        """
        接收采购订单货物
        
        参数:
            po_id: 采购订单ID
            receipt_data: 收货数据字典
        
        返回:
            收货ID
        """
        # 验证订单是否存在且已确认
        if po_id not in self.purchase_orders_df['po_id'].values:
            raise ValueError(f"采购订单不存在: {po_id}")
        
        order_status = self.purchase_orders_df.loc[
            self.purchase_orders_df['po_id'] == po_id, 
            'status'
        ].iloc[0]
        
        if order_status != '已确认':
            raise ValueError(f"采购订单未确认，无法接收: {po_id}")
        
        # 验证必要字段
        required_fields = ['item_id', 'received_quantity', 'receiver']
        for field in required_fields:
            if field not in receipt_data:
                raise ValueError(f"缺少必要字段: {field}")
        
        # 验证订单项是否存在
        item_id = receipt_data['item_id']
        item = self.purchase_items_df[
            (self.purchase_items_df['po_id'] == po_id) & 
            (self.purchase_items_df['item_id'] == item_id)
        ]
        
        if len(item) == 0:
            raise ValueError(f"订单项不存在: {item_id}")
        
        # 验证收货数量
        ordered_quantity = item['quantity'].iloc[0]
        already_received = item['received_quantity'].iloc[0]
        to_receive = receipt_data['received_quantity']
        
        if already_received + to_receive > ordered_quantity:
            raise ValueError(f"收货数量超过订单数量: {already_received + to_receive} > {ordered_quantity}")
        
        # 生成收货ID
        receipt_id = str(uuid.uuid4())
        
        # 准备收货数据
        receipt_data['receipt_id'] = receipt_id
        receipt_data['po_id'] = po_id
        receipt_data['receipt_date'] = receipt_data.get('receipt_date', datetime.now().strftime('%Y-%m-%d'))
        receipt_data['delivery_note_number'] = receipt_data.get('delivery_note_number', '')
        receipt_data['carrier'] = receipt_data.get('carrier', '')
        receipt_data['status'] = '待检验'
        receipt_data['notes'] = receipt_data.get('notes', '')
        
        # 添加到数据框
        self.receipts_df = pd.concat([
            self.receipts_df, 
            pd.DataFrame([receipt_data])
        ], ignore_index=True)
        
        # 更新订单项的收货数量
        self.purchase_items_df.loc[
            self.purchase_items_df['item_id'] == item_id, 
            'received_quantity'
        ] = already_received + to_receive
        
        # 更新订单项状态
        if already_received + to_receive == ordered_quantity:
            self.purchase_items_df.loc[
                self.purchase_items_df['item_id'] == item_id, 
                'status'
            ] = '已收货'
        else:
            self.purchase_items_df.loc[
                self.purchase_items_df['item_id'] == item_id, 
                'status'
            ] = '部分收货'
        
        # 检查订单是否全部收货
        order_items = self.purchase_items_df[self.purchase_items_df['po_id'] == po_id]
        if all(item['status'] in ['已收货', '已取消'] for _, item in order_items.iterrows()):
            self.purchase_orders_df.loc[
                self.purchase_orders_df['po_id'] == po_id, 
                'status'
            ] = '已收货'
        elif any(item['status'] in ['部分收货', '已收货'] for _, item in order_items.iterrows()):
            self.purchase_orders_df.loc[
                self.purchase_orders_df['po_id'] == po_id, 
                'status'
            ] = '部分收货'
        
        # 保存数据
        self.receipts_df.to_csv(os.path.join(self.data_path, 'purchase_receipts.csv'), index=False)
        self.purchase_items_df.to_csv(os.path.join(self.data_path, 'purchase_order_items.csv'), index=False)
        self.purchase_orders_df.to_csv(os.path.join(self.data_path, 'purchase_orders.csv'), index=False)
        
        return receipt_id
    
    def inspect_receipt(self, receipt_id, inspection_data):
        """
        检验收货
        
        参数:
            receipt_id: 收货ID
            inspection_data: 检验数据字典
        
        返回:
            检验ID
        """
        # 验证收货是否存在
        if receipt_id not in self.receipts_df['receipt_id'].values:
            raise ValueError(f"收货记录不存在: {receipt_id}")
        
        receipt = self.receipts_df[self.receipts_df['receipt_id'] == receipt_id].iloc[0]
        
        if receipt['status'] != '待检验':
            raise ValueError(f"收货已检验: {receipt_id}")
        
        # 验证必要字段
        required_fields = ['inspector', 'accepted_quantity', 'rejected_quantity']
        for field in required_fields:
            if field not in inspection_data:
                raise ValueError(f"缺少必要字段: {field}")
        
        # 验证检验数量
        received_quantity = receipt['received_quantity']
        accepted_quantity = inspection_data['accepted_quantity']
        rejected_quantity = inspection_data['rejected_quantity']
        
        if accepted_quantity + rejected_quantity != received_quantity:
            raise ValueError(f"检验数量不匹配: {accepted_quantity} + {rejected_quantity} != {received_quantity}")
        
        # 生成检验ID
        inspection_id = str(uuid.uuid4())
        
        # 准备检验数据
        inspection_data['inspection_id'] = inspection_id
        inspection_data['receipt_id'] = receipt_id
        inspection_data['po_id'] = receipt['po_id']
        inspection_data['item_id'] = receipt['item_id']
        inspection_data['inspection_date'] = inspection_data.get('inspection_date', datetime.now().strftime('%Y-%m-%d'))
        inspection_data['rejection_reason'] = inspection_data.get('rejection_reason', '')
        inspection_data['status'] = '已完成'
        inspection_data['notes'] = inspection_data.get('notes', '')
        
        # 添加到数据框
        self.quality_inspections_df = pd.concat([
            self.quality_inspections_df, 
            pd.DataFrame([inspection_data])
        ], ignore_index=True)
        
        # 更新收货状态
        self.receipts_df.loc[
            self.receipts_df['receipt_id'] == receipt_id, 
            'status'
        ] = '已检验'
        
        # 更新订单项的接收和拒绝数量
        item_id = receipt['item_id']
        
        current_accepted = self.purchase_items_df.loc[
            self.purchase_items_df['item_id'] == item_id, 
            'accepted_quantity'
        ].iloc[0]
        
        current_rejected = self.purchase_items_df.loc[
            self.purchase_items_df['item_id'] == item_id, 
            'rejected_quantity'
        ].iloc[0]
        
        self.purchase_items_df.loc[
            self.purchase_items_df['item_id'] == item_id, 
            'accepted_quantity'
        ] = current_accepted + accepted_quantity
        
        self.purchase_items_df.loc[
            self.purchase_items_df['item_id'] == item_id, 
            'rejected_quantity'
        ] = current_rejected + rejected_quantity
        
        # 保存数据
        self.quality_inspections_df.to_csv(os.path.join(self.data_path, 'quality_inspections.csv'), index=False)
        self.receipts_df.to_csv(os.path.join(self.data_path, 'purchase_receipts.csv'), index=False)
        self.purchase_items_df.to_csv(os.path.join(self.data_path, 'purchase_order_items.csv'), index=False)
        
        return inspection_id
    
    def get_purchase_order_tracking(self, po_id):
        """
        获取采购订单跟踪信息
        
        参数:
            po_id: 采购订单ID
        
        返回:
            跟踪信息字典
        """
        if po_id not in self.purchase_orders_df['po_id'].values:
            return None
        
        # 获取订单基本信息
        order_data = self.purchase_orders_df[self.purchase_orders_df['po_id'] == po_id].iloc[0].to_dict()
        
        # 获取订单项
        order_items = []
        for _, item in self.purchase_items_df[self.purchase_items_df['po_id'] == po_id].iterrows():
            item_data = item.to_dict()
            
            # 获取收货记录
            receipts = self.receipts_df[
                (self.receipts_df['po_id'] == po_id) & 
                (self.receipts_df['item_id'] == item_data['item_id'])
            ].to_dict('records')
            item_data['receipts'] = receipts
            
            # 获取检验记录
            inspections = self.quality_inspections_df[
                (self.quality_inspections_df['po_id'] == po_id) & 
                (self.quality_inspections_df['item_id'] == item_data['item_id'])
            ].to_dict('records')
            item_data['inspections'] = inspections
            
            order_items.append(item_data)
        
        order_data['items'] = order_items
        
        # 获取审批记录
        approval_status = self.get_approval_status(po_id, 'order')
        order_data['approval_status'] = approval_status
        
        return order_data
    
    def generate_purchase_plan(self, days=30, min_stock_level=None):
        """
        生成采购计划
        
        参数:
            days: 计划天数
            min_stock_level: 最小库存水平字典 {product_id: min_level}
        
        返回:
            采购计划列表
        """
        # 这里需要集成库存分析和需求预测功能
        # 简化版本：基于当前库存和最小库存水平生成采购计划
        
        if min_stock_level is None:
            min_stock_level = {}
        
        # 假设我们有库存数据
        try:
            inventory_df = pd.read_csv(os.path.join(self.data_path, 'inventory.csv'))
        except FileNotFoundError:
            return []
        
        # 生成采购计划
        purchase_plan = []
        
        for _, product in self.products_df.iterrows():
            product_id = product['product_id']
            
            # 获取当前库存
            current_stock = 0
            product_inventory = inventory_df[inventory_df['product_id'] == product_id]
            if len(product_inventory) > 0:
                current_stock = product_inventory['quantity'].iloc[0]
            
            # 获取最小库存水平
            min_level = min_stock_level.get(product_id, 0)
            
            # 如果当前库存低于最小水平，生成采购计划
            if current_stock < min_level:
                plan_item = {
                    'product_id': product_id,
                    'product_name': product['name'],
                    'current_stock': current_stock,
                    'min_stock_level': min_level,
                    'suggested_order_quantity': min_level - current_stock,
                    'suggested_order_date': datetime.now().strftime('%Y-%m-%d'),
                    'priority': 'high' if current_stock == 0 else 'medium'
                }
                purchase_plan.append(plan_item)
        
        return purchase_plan
    
    def get_purchase_statistics(self, start_date=None, end_date=None, supplier_id=None):
        """
        获取采购统计信息
        
        参数:
            start_date: 开始日期
            end_date: 结束日期
            supplier_id: 供应商ID
        
        返回:
            统计信息字典
        """
        # 过滤订单
        orders_df = self.purchase_orders_df.copy()
        
        if start_date:
            orders_df = orders_df[orders_df['order_date'] >= start_date]
        
        if end_date:
            orders_df = orders_df[orders_df['order_date'] <= end_date]
        
        if supplier_id:
            orders_df = orders_df[orders_df['supplier_id'] == supplier_id]
        
        if len(orders_df) == 0:
            return {
                'total_orders': 0,
                'total_amount': 0,
                'average_order_value': 0,
                'status_distribution': {},
                'supplier_distribution': {},
                'monthly_trend': {}
            }
        
        # 计算统计信息
        total_orders = len(orders_df)
        total_amount = orders_df['total_amount'].sum()
        average_order_value = total_amount / total_orders if total_orders > 0 else 0
        
        # 状态分布
        status_distribution = orders_df['status'].value_counts().to_dict()
        
        # 供应商分布
        supplier_distribution = orders_df['supplier_id'].value_counts().to_dict()
        
        # 月度趋势
        orders_df['month'] = pd.to_datetime(orders_df['order_date']).dt.strftime('%Y-%m')
        monthly_trend = orders_df.groupby('month')['total_amount'].sum().to_dict()
        
        return {
            'total_orders': total_orders,
            'total_amount': total_amount,
            'average_order_value': average_order_value,
            'status_distribution': status_distribution,
            'supplier_distribution': supplier_distribution,
            'monthly_trend': monthly_trend
        }
    
    def export_purchase_orders(self, start_date=None, end_date=None, supplier_id=None, output_path=None):
        """
        导出采购订单
        
        参数:
            start_date: 开始日期
            end_date: 结束日期
            supplier_id: 供应商ID
            output_path: 输出路径
        
        返回:
            导出文件路径
        """
        # 过滤订单
        orders_df = self.purchase_orders_df.copy()
        
        if start_date:
            orders_df = orders_df[orders_df['order_date'] >= start_date]
        
        if end_date:
            orders_df = orders_df[orders_df['order_date'] <= end_date]
        
        if supplier_id:
            orders_df = orders_df[orders_df['supplier_id'] == supplier_id]
        
        if len(orders_df) == 0:
            return None
        
        # 准备导出数据
        export_data = []
        
        for _, order in orders_df.iterrows():
            order_data = order.to_dict()
            
            # 获取供应商信息
            supplier_id = order_data['supplier_id']
            supplier = self.suppliers_df[self.suppliers_df['supplier_id'] == supplier_id]
            if len(supplier) > 0:
                order_data['supplier_name'] = supplier['name'].iloc[0]
            else:
                order_data['supplier_name'] = '未知供应商'
            
            # 获取订单项
            items = self.purchase_items_df[self.purchase_items_df['po_id'] == order_data['po_id']]
            order_items = []
            
            for _, item in items.iterrows():
                item_data = item.to_dict()
                
                # 获取产品信息
                product_id = item_data['product_id']
                product = self.products_df[self.products_df['product_id'] == product_id]
                if len(product) > 0:
                    item_data['product_name'] = product['name'].iloc[0]
                    item_data['product_category'] = product['category'].iloc[0]
                    item_data['product_unit'] = product['unit'].iloc[0]
                else:
                    item_data['product_name'] = '未知产品'
                    item_data['product_category'] = '未知类别'
                    item_data['product_unit'] = '个'
                
                order_items.append(item_data)
            
            order_data['items'] = order_items
            export_data.append(order_data)
        
        # 导出为JSON
        if output_path is None:
            output_dir = Path('reports')
            output_dir.mkdir(exist_ok=True)
            output_path = output_dir / 'purchase_orders_export.json'
        
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(export_data, f, ensure_ascii=False, indent=2)
        
        return str(output_path)


# 如果直接运行此脚本
if __name__ == "__main__":
    # 创建采购订单管理实例
    pom = PurchaseOrderManager()
    
    # 示例：创建采购申请
    requisition = {
        'requester': '张工程师',
        'department': '研发部',
        'product_id': 'PROD001',  # 假设产品存在
        'quantity': 10,
        'required_date': '2025-09-01',
        'purpose': '新产品开发'
    }
    
    try:
        req_id = pom.create_purchase_requisition(requisition)
        print(f"已创建采购申请，ID: {req_id}")
        
        # 示例：审批采购申请
        pom.approve_workflow(req_id, 'requisition', '部门经理', '通过', '同意采购')
        print("部门经理已审批")
        
        pom.approve_workflow(req_id, 'requisition', '采购经理', '通过', '价格合理')
        print("采购经理已审批")
        
        # 示例：从采购申请创建采购订单
        po_id = pom.create_purchase_order_from_requisition([req_id], 'SUP10001')  # 假设供应商存在
        print(f"已创建采购订单，ID: {po_id}")
        
        # 示例：审批采购订单
        pom.approve_workflow(po_id, 'order', '采购经理', '通过', '符合采购政策')
        pom.approve_workflow(po_id, 'order', '财务经理', '通过', '预算充足')
        pom.approve_workflow(po_id, 'order', '总经理', '通过', '同意采购')
        print("采购订单已审批")
        
        # 示例：接收采购订单货物
        receipt_data = {
            'item_id': pom.purchase_items_df[pom.purchase_items_df['po_id'] == po_id]['item_id'].iloc[0],
            'received_quantity': 10,
            'receiver': '李仓管',
            'delivery_note_number': 'DN-2025-001'
        }
        
        receipt_id = pom.receive_purchase_order(po_id, receipt_data)
        print(f"已接收货物，收货ID: {receipt_id}")
        
        # 示例：检验收货
        inspection_data = {
            'inspector': '王质检',
            'accepted_quantity': 9,
            'rejected_quantity': 1,
            'rejection_reason': '外观损坏'
        }
        
        inspection_id = pom.inspect_receipt(receipt_id, inspection_data)
        print(f"已完成质检，检验ID: {inspection_id}")
        
    except ValueError as e:
        print(f"错误: {e}")
